<template>
    <div class="app-container">
        <div class="filter-container">
            <header>
                <el-button size="small" type="primary" icon="el-icon-plus" @click="toAddAdvertisement()">新增</el-button>
                <el-button size="small" type="danger" icon="el-icon-delete" @click="toDeleteAll()">批量删除</el-button>
            </header>
            <article>
                <el-table border :data="dataList" ref="multipleTable" @sort-change="getOrder" @selection-change="handleSelectionChange">
                    <el-table-column fixed="left" type="selection" width="40">
                    </el-table-column>
                    <el-table-column prop="name" label="广告位标题" align="center" min-width="100px" >
                    </el-table-column>
                    <el-table-column label="链接" align="center" min-width="200px">
                      <template slot-scope="scope">
                        {{scope.row.url}}
                      </template>
                    </el-table-column>
                    <el-table-column label="图片" align="center" min-width="100px">
                      <template slot-scope="scope">
                        <el-popover placement="top-start" trigger="hover">
                          <img :src="scope.row.imageCn" class="previewImage">
                          <img :src="scope.row.imageCn" class="thumbnail" slot="reference">
                        </el-popover>
                      </template>
                    </el-table-column>
                    <el-table-column label="生效时间" align="center" width="200px">
                      <template slot-scope="scope">
                        {{scope.row.startTime}} 至 {{scope.row.endTime}}
                      </template>
                    </el-table-column>
                    <el-table-column label="广告位移动" align="center" width="220px">
                      <template slot-scope="scope">
                        <el-input-number v-model="scope.row.sort" controls-position="right" :min="0" size="mini" :precision="0"></el-input-number>
                        <el-button type="primary" plain @click="toSort(scope.row.sort,scope.row.id)" size="mini" style="margin-left:5px">排序</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" align="center" width="180px">
                        <template slot-scope="scope">
                            <el-button plain type="primary" size="mini" @click="toDditProduct(scope.row)">编辑</el-button>
                            <el-button plain type="danger" size="mini" @click="toDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                  </el-table>
                  <list-pagination :total="total" :page="page" :pageSize="pageSize" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></list-pagination>
            </article>
            <el-dialog
            title="提示"
            :visible="dialogVisible"
            width="800px"
            :before-close="handleClose">
              <div style="height: 100%; width: 100%">
                <el-form :rules="adDialogRules" ref="ad" :model="ad" label-position="right" label-width="160px" class="demo-ruleForm" style='margin-left:50px;'>
                  <el-form-item hide-required-asterisk="false" :label="adDialogTitles.name" prop="name" style="width:400px">
                    <el-input v-model="ad.name" size="medium" placeholder="请输入内容" maxlength="20"></el-input>
                  </el-form-item>
                  <el-form-item :label="adDialogTitles.urlId" prop="url" style="width:400px">
                    <el-input v-model="ad.urlId" size="medium" placeholder="请输入内容"></el-input>
                  </el-form-item>
                  <el-form-item :label="adDialogTitles.imageCn" prop="imageCn">
                    <el-upload
                      class="uploader"
                      multiple
                      :headers="headers"
                      :file-list="imgList"
                      :action="uploadFileUrl"
                      :limit="1"
                      accept="image/jpeg,image/jpg,image/png"
                      :before-upload="onBeforeUpload"
                      :on-remove="handleUploaderRemove"
                      :on-success="handleUploaderSuccess"
                      :name="uploadFileName"
                      list-type="picture-card"
                      >
                      <i class="el-icon-plus"></i>
                      <div class="el-upload__tip" slot="tip">建议尺寸：335*170像素以上，大小2M以下；支持jpg、jpeg、png；只能上传一张图片。</div>
                    </el-upload>
                  </el-form-item>
                  <el-form-item :label="adDialogTitles.imageEn" prop="imageEn">
                    <el-upload
                      class="uploader"
                      multiple
                      :headers="headers"
                      :file-list="imgList"
                      :action="uploadFileUrl"
                      :limit="1"
                      accept="image/jpeg,image/jpg,image/png"
                      :on-remove="handleUploadRemove"
                      :on-success="handleUploadSuccess"
                      :name="uploadFileName"
                      list-type="picture-card"
                      >
                      <i class="el-icon-plus"></i>
                      <div class="el-upload__tip" slot="tip">建议尺寸：335*170像素以上，大小2M以下；支持jpg、jpeg、png；只能上传一张图片。</div>
                    </el-upload>
                  </el-form-item>
                  <el-form-item :label="adDialogTitles.startTime" prop="startTime">
                  <el-date-picker size="medium" v-model="ad.startTime" type="datetime" placeholder="请输入开始时间" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                  </el-form-item>
                  <el-form-item :label="adDialogTitles.endTime" prop="endTime">
                  <el-date-picker size="medium" v-model="ad.endTime" type="datetime" :picker-options="pickerOptions" placeholder="请输入结束时间" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                  </el-form-item>
                </el-form>
              </div>
              <span slot="footer" class="dialog-footer">
                  <el-button size="small" @click="cancel(ad)">取 消</el-button>
                  <el-button size="small" type="primary" @click="toAddSortList(ad)">确 定</el-button>
              </span>
          </el-dialog>
        </div>
    </div>
</template>
<script>
import addAdvertiseman from '@/views/operation/components/AddAdvertiseman.vue'
import list from '@/mixins/List'
import listPagination from '@/components/ListPagination'
import {
  listBanner, deleteBanner, changeBannerSort, batchDeleteBanner, insertBanner, updateBanner
} from '@/api/banner'
export default {
  name: 'screenAdList',
  mixins: [list],
  data () {
    const validateStopTime = (rule, value, callback) => {
      const startTime = new Date(this.ad.startTime)
      const stopTime = new Date(this.ad.stopTime)
      if (startTime >= stopTime) {
        callback(new Error('结束时间不能小于开始时间'))
      } else {
        callback()
      }
    }
    // const validateUrl = (rule, value, callback) => {
    //   if (this.ad.url && this.ad.url.length > 0 && !validator.isURL(this.ad.url, { require_protocol: true })) {
    //     callback(new Error())
    //   } else {
    //     callback()
    //   }
    // }
    return {
      dataList: [],
      dialogVisible: false,
      multipleSelection: [],
      dataListId: [],
      goodSort: '',
      operationId: '',
      bannerLsitSort: '',
      deteles: '',
      banner: '',
      operationRow: {},
      fatheraddAdvertiseman: false,
      bannerList: '',
      uploadFileUrl: `${process.env.VUE_APP_UPLOAD_API}`,
      uploadFileName: `${process.env.VUE_APP_UPLOAD_NAME}`,
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      adDialogTitles: {
        name: '广告标题：',
        urlId: '广告商品ID：',
        url: '广告地址url：',
        imageCn: '中文广告图：',
        imageEn: '英文广告图：',
        startTime: '广告开始时间：',
        endTime: '广告结束时间：'
      },
      adDialogRules: {
        name: [{ required: true, message: '标题不能为空', trigger: 'change' }],
        url: [
          { required: false, message: '广告 Url 格式不正确', trigger: 'change' }
        ],
        imageCn: [
          { required: true, message: '图片不能为空', trigger: 'change' }
        ],
        imageEn: [
          { required: true, message: '图片不能为空', trigger: 'change' }
        ],
        startTime: [{ type: 'string', required: true, message: '初始时间不能为空', trigger: 'change' }],
        endTime: [
          { required: true, message: '结束时间不能为空', trigger: 'change' },
          { validator: validateStopTime, message: '结束时间不能小于开始时间', trigger: 'change' }
        ]
      },
      ad: {
        name: '',
        urlId: '',
        url: '',
        imageCn: '',
        imageEn: '',
        startTime: '',
        endTime: ''
      },
      imgList: [],
      imgLists: [],
      headers: this.$headers,
      bannerUrl: `${process.env.VUE_APP_BANNER_URL}`
    }
  },
  components: {
    addAdvertiseman,
    listPagination
  },
  watch: {
    multipleSelection: function () {
      let arr = []
      for (let i in this.multipleSelection) {
        arr.push(this.multipleSelection[i].id)
      }
      this.dataListId = arr
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    async getList () {
      let { data } = await listBanner({
        pageNum: this.page,
        pageSize: this.pageSize
      })
      this.dataList = data.list
      this.total = data.total
    },
    toAddAdvertisement () {
      this.imgList = []
      this.imgLists = []
      this.ad = {
        name: '',
        id: '',
        url: '',
        imageCn: '',
        imageEn: '',
        startTime: '',
        endTime: ''
      }
      this.bannerList = 'addOperationList'
      if (this.$refs['ad'] !== undefined) {
        this.$refs['ad'].resetFields()
      }
      this.dialogVisible = true
    },
    toDeleteAll () {
      if (this.dataListId.length === 0) {
        this.$message('请先勾选您需操作的商品')
        return
      }
      this.$confirm('此操作将永久删除所选广告位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var str = ''
        for (let item of this.dataListId) {
          str += item + ','
        }
        str = str.substr(0, str.length - 1)
        batchDeleteBanner({ 'ids': str }).then(res => {
          if (res.code === 200) {
            this.getList()
            this.dialogVisible = false
            this.$message.success('删除成功')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    toSort (sort, id) {
      changeBannerSort({
        'sort': sort,
        'id': id
      }).then(res => {
        if (res.code === 200) {
          this.getList()
          this.$message.success('操作成功')
        }
      })
    },
    toggleSelection (rows) {
      rows.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row)
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    getOrder (param) {
      console.log(param)
    },
    toMove (index) {
      console.log(index)
    },
    toDditProduct (row) {
      if (this.$refs['ad'] !== undefined) {
        this.$nextTick(() => {
          this.$refs['ad'].clearValidate()
        })
      }
      this.imgList = []
      this.imgLists = []
      if (row.imageEn !== '') {
        this.imgList = [{ name: 'imageEn', url: row.imageEn }]
      }
      if (row.imageCn !== '') {
        this.imgLists = [{ name: 'imageCn', url: row.imageCn }]
      }
      this.bannerList = 'updateOperationList'
      this.ad = JSON.parse(JSON.stringify(row))
      this.imgList = [{ name: 'imageCn', url: row.imageCn }]
      this.imgLists = [{ name: 'imageEn', url: row.imageEn }]
      let list = this.ad.url.split('=')
      if (list.length === 2) {
        this.ad.urlId = list[1]
      }
      this.dialogVisible = true
    },
    toDelete (row) {
      this.operationId = row.id
      this.$confirm('此操作将永久删除所选广告位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBanner({ 'id': this.operationId }).then(res => {
          if (res.code === 200) {
            this.dialogVisible = false
            this.$message.success('删除成功')
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleClose () {
      this.imgList = []
      this.imgLists = []
      this.dialogVisible = false
    },
    cancel () {
      this.imgList = []
      this.imgLists = []
      this.dialogVisible = false
    },
    insertBannerList () {
      insertBanner(this.ad).then(data => {
        if (data.code === 200) {
          this.getList()
          this.dialogVisible = false
          this.$message.success('新增成功')
        }
      })
    },
    updateBanner () {
      updateBanner(this.ad).then(data => {
        if (data.code === 200) {
          this.getList()
          this.dialogVisible = false
          this.$message.success('编辑成功')
        }
      })
    },
    toAddSortList (ad) {
      this.$refs['ad'].validate((valid) => {
        if (valid) {
          this.ad.url = ''
          if (this.ad.urlId) {
            this.ad.url = `${this.bannerUrl}${this.ad.urlId}`
          }
          if (this.bannerList === 'addOperationList') {
            this.insertBannerList()
          } else if (this.bannerList === 'updateOperationList') {
            this.updateBanner()
          }
        }
      })
    },
    onBeforeUpload (file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isIMAGE && isLt2M
    },
    handleUploaderRemove (file, fileList) {
      this.ad.imageCn = ''
    },
    handleUploaderSuccess (response, file, fileList) {
      this.ad.imageCn = response.data
      this.$message({ message: '上传成功', type: 'success' })
    },
    handleUploadRemove (file, fileList) {
      this.ad.imageEn = ''
    },
    handleUploadSuccess (response, file, fileList) {
      this.ad.imageEn = response.data
      this.$message({ message: '上传成功', type: 'success' })
    }
  }
}
</script>
<style lang="scss" scoped>
    header{
        width: 100%;
        height: 48px;
    }
    article{

    }
</style>
